package com.bright.multiphoto;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Base64;
import android.util.Log;

@SuppressLint("NewApi")
public class Base64Util {
	private static String TAG = "Base64Util";
	private static final int reqWidth = 1280;

	/** 计算图片的缩放比例 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		int height = options.outHeight;
		int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			int heightRatio = Math.round((float) height / (float) reqHeight);
			int widthRatio = Math.round((float) width / (float) reqWidth);
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}
		Log.d(TAG, "inSampleSize=" + inSampleSize);
		return inSampleSize;
	}

	/** 根据路径获得图片并压缩，返回bitmap用于显示 */
	public static Bitmap getSmallBitmap(String filePath, int reqWidth,
			int reqHeight) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		Bitmap bitMap = BitmapFactory.decodeFile(filePath, options);// 此时返回
																	// bitMap 为空

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		options.inInputShareable = true;// 当系统内存不够时候图片自动被回收

		bitMap = BitmapFactory.decodeFile(filePath, options);
		return bitMap;
	}

	/** 把bitmap转换成String */
	public static String bitmapToString(String filePath, int reqWidth) {
		Bitmap bm = getSmallBitmap(filePath, reqWidth, reqWidth);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
		byte[] b = baos.toByteArray();

		bm.recycle();
		bm = null;

		return Base64.encodeToString(b, Base64.DEFAULT);
	}

	/**
	 * 根据图片路径进行 Base64编码后返回字符串
	 * 
	 * @param filePath
	 *            filePath
	 * @param size
	 * 
	 * @return String
	 */
	public static String compress(String filePath) {
		if(filePath.startsWith("file://")){
			filePath = filePath.replace("file://", "");
		}
		
		String resultString = null;
		ByteArrayOutputStream writeOut = null;
		Bitmap bmap = null;
		BitmapFactory.Options options = null;
		try {
			options = new BitmapFactory.Options();
			writeOut = new ByteArrayOutputStream();

			options.inJustDecodeBounds = true;
			bmap = BitmapFactory.decodeFile(filePath, options);

			Log.e(TAG, "outWidth::" + options.outWidth + ",outHeight::"
					+ options.outHeight);

			options.inSampleSize = calculateInSampleSize(options, reqWidth,
					reqWidth);
			options.inJustDecodeBounds = false;

			bmap = BitmapFactory.decodeFile(filePath, options);
			bmap.compress(Bitmap.CompressFormat.JPEG, 40, writeOut);
			Log.e(TAG,
					"resWidth::" + bmap.getWidth() + ",resHeight::"
							+ bmap.getHeight());
			byte[] b = writeOut.toByteArray();
			resultString = Base64
					.encodeToString(b, 0, b.length, Base64.DEFAULT);
			Log.e(TAG, "base64后的长度=" + resultString.getBytes().length / 1024f / 1024f);
			return resultString;

		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != writeOut) {
					writeOut.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return resultString;
	}
	
	/**
	 * 根据Bitmap进行 Base64编码后返回字符串
	 * 
	 * @param Bitmap
	 *            bitmap
	 * 
	 * @return String
	 */
	public static String compress(Bitmap bitmap) {
		String resultString = null;
		ByteArrayOutputStream writeOut = null;
		try {
			writeOut = new ByteArrayOutputStream();
			bitmap.compress(Bitmap.CompressFormat.JPEG, 40, writeOut);
			Log.e(TAG,
					"resWidth::" + bitmap.getWidth() + ",resHeight::"
							+ bitmap.getHeight());
			byte[] b = writeOut.toByteArray();
			resultString = Base64
					.encodeToString(b, 0, b.length, Base64.DEFAULT);
			Log.e(TAG, "base64后的长度=" + resultString.getBytes().length / 1024f / 1024f);
			return resultString;

		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != writeOut) {
					writeOut.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return resultString;
	}

	public synchronized static Bitmap compress(Bitmap bm, int size) {
		Log.d(TAG, "bm�?==::" + bm.getByteCount());
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
		Log.d(TAG, "out-bm-�?==::" + out.toByteArray().length);
		if (out.toByteArray().length <= size * 1024) {
			return bm;
		}
		float zoom = (float) Math.sqrt(size * 1024
				/ (float) out.toByteArray().length);
		Matrix matrix = new Matrix();
		matrix.setScale(zoom, zoom);
		Bitmap result = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
				bm.getHeight(), matrix, true);
		out.reset();
		result.compress(Bitmap.CompressFormat.JPEG, 90, out);
		while (out.toByteArray().length > size * 1024) {
			Log.d(TAG, String.valueOf(out.toByteArray().length));
			matrix.setScale(0.9f, 0.9f);
			result = Bitmap.createBitmap(result, 0, 0, result.getWidth(),
					result.getHeight(), matrix, true);
			out.reset();
			// 90 是压缩率，表示压�?0%; 如果不压缩是100，表示压缩率�?
			result.compress(Bitmap.CompressFormat.JPEG, 90, out);
		}
		byte[] buffer = out.toByteArray();
		Log.d(TAG, "bm�?==::" + result.getByteCount());
		Log.d(TAG, "out-bm-�?==::" + buffer.length);
		return result;
	}

	/** 文件的大小 */
	public static int getFileSize(String pathImage) {
		File file1 = null;
		FileInputStream in1 = null;
		int fileSize1 = 0;
		try {
			file1 = new File(pathImage);
			in1 = new FileInputStream(file1);
			fileSize1 = in1.available();
			Log.e("TestBase64Util", "图片 --> 文件大小=" + fileSize1);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != in1) {
				try {
					in1.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != file1) {
				file1 = null;
			}
		}
		return fileSize1;
	}
}
